<?php
/**
 * Created by PhpStorm.
 * User: kankan
 * Date: 2020-05-14
 * Time: 11:00
 */

namespace App\Services;


class MapServices
{
    private $host = 'https://apis.map.qq.com';
    private $key  = 'FLMBZ-ZFNRW-MMARW-RAV7P-FALZF-HLFOL';
    private $sk   = 'dlxxUxfU2mjTJkoirzKG8Hq8i1C9PlV';


    /**
     * WebServiceAPI（GET方法）签名计算
     *
     * @param string  $route 请求路径
     * @param array   $data  请求参数
     * @param         $sk
     *
     * @return bool|string
     */
    private function getSign($route, array $data, $sk)
    {
        $str = '';
        ksort($data);
        foreach ($data as $key => $value) {
            if (!empty($str)) {
                $str .= '&';
            }
            $str .= $key . '=' . (is_bool($value) ? ($value == true ? 'true' : 'false') : $value);
        }

        $encrypt_str = $route . '?' . $str . $sk;

        return md5($encrypt_str);
    }

    /**
     * 地点搜索（search接口），提供三类范围条件的搜索功能
     *
     * @param $keyword
     * @param $boundary
     *
     * @return string
     */
    public function search($keyword, $boundary)
    {
        $route  = '/ws/place/v1/search';
        $data   = [
            'keyword'  => $keyword,
            'boundary' => $boundary,
            'key'      => $this->key
        ];
        $sign   = $this->getSign($route, $data, $this->sk);
        $args   = array_merge($data, ['sig' => $sign]);
        $result = CurlServices::get($this->host . $route, $args);

        return $result;
    }

    /**
     * 获取行政区域列表
     *
     * @return string
     */
    public function districtList()
    {
        $route  = '/ws/district/v1/list';
        $data   = [
            'key' => $this->key
        ];
        $sign   = $this->getSign($route, $data, $this->sk);
        $args   = array_merge($data, ['sig' => $sign]);
        $result = CurlServices::get($this->host . $route, $args);

        return $result;
    }


    /**
     * 获取指定行政区划的子级行政区划
     *
     * @param $id
     *
     * @return string
     */
    public function getChildren($id = null)
    {
        $route  = '/ws/district/v1/getchildren';
        $data   = [
            'key' => $this->key,
            'id'  => $id
        ];
        $sign   = $this->getSign($route, $data, $this->sk);
        $args   = array_merge($data, ['sig' => $sign]);
        $result = CurlServices::get($this->host . $route, $args);

        return $result;
    }

    /**
     * 根据关键词搜索行政区划
     *
     * @param $keyword
     *
     * @return string
     */
    public function searchDistrictByKeyWords($keyword)
    {
        $route  = '/ws/district/v1/getchildren';
        $data   = [
            'key'     => $this->key,
            'keyword' => $keyword
        ];
        $sign   = $this->getSign($route, $data, $this->sk);
        $args   = array_merge($data, ['sig' => $sign]);
        $result = CurlServices::get($this->host . $route, $args);

        return $result;
    }

}